from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from rest_framework.pagination import PageNumberPagination
from rest_framework import status
# from s_server.tools.data_handler import get_code_kl_states
from s_server.tools.s_client import get_code_infos, get_stp_infos
# from s_server.models import Record, Codes
from s_server.tools.moni import moni_by_code, moni_by_code_with_range_day
from s_server.serializers_tools import *
from s_server.deeplearning.datamaker import OriginData
import numpy as np


# Create your views here.
class GetCodeInfos(APIView):
    """
    获取告警表中告警数据
    """

    # authentication_classes = (JSONWebTokenAuthentication,)
    # permission_classes = (AdminIsAuthenticatedPermission,)
    # http_method_names = ['get']
    # # ordering_fields = ('-update_time')
    # filterset_class = ZabbixAlarmViewFilter
    # filter_backends = (filters.DjangoFilterBackend,)
    @staticmethod
    def get(request, *args, **kwargs):
        get_code_infos()
        return Response(status=status.HTTP_204_NO_CONTENT)


class CodeDataHasLastView(APIView):
    """
    CodesView
    """

    @staticmethod
    def get(request, *args, **kwargs):
        _code = request.query_params["code"]
        records = Record.objects.filter(dm_id_id=_code)
        if len(records) > 120:
            return Response(status=status.HTTP_200_OK)
        else:
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class CodesView(ModelViewSet):
    """
    CodesView
    """
    queryset = Codes.objects.all().order_by('mc')
    serializer_class = CodesSerializer
    http_method_names = ['get']
    # ordering_fields = ('-update_time')
    # filterset_class =  CodesFilter
    # filter_backends = (filters.DjangoFilterBackend,)


class GetSTPInfos(APIView):
    """
    获取告警表中告警数据
    """

    def get(self, request, *args, **kwargs):
        res = get_stp_infos()
        return Response(status=status.HTTP_200_OK, data={"result": "ok"})


# class GetABPQInfos(APIView):
#     """
#     """
#
#     @staticmethod
#     def get(request, *args, **kwargs):
#         codes = [i["dm_id_id"] for i in Record.objects.filter(d="2024-03-01").values("dm_id_id")]
#         code_kl_state_dict = get_code_kl_states(codes)
#         return Response(status=status.HTTP_204_NO_CONTENT, data=code_kl_state_dict)


class Moni(APIView):
    """
    """

    @staticmethod
    def get(request, *args, **kwargs):
        print(request.query_params)
        _code = request.query_params["code"]
        _start_day = request.query_params["start_day"]
        _all_money = request.query_params["all_money"]
        _times_percent = request.query_params["times_percent"]
        _a_times = float(request.query_params["at"])
        _b_times = float(request.query_params["bt"])
        # http://127.0.0.1:18080/s_server/moni/?code=300684&start_day=1300&all_money=100000
        data = {"code": _code,
                "start_day": _start_day,
                "all_money": _all_money
                }
        last_money = moni_by_code(
            data["code"], int(data["start_day"]), int(data["all_money"]), _times_percent,
            _a_times, _b_times
        )

        data.update({"last_money": last_money})
        print("结尾")
        return Response(data=data)


import random


def random_data(my_list, number):
    # 创建一个列表
    id_list = []
    for i in range(number):
        selected_data = random.sample(my_list, 1)
        # print(selected_data[0])
        if selected_data[0] not in id_list:
            id_list.append(selected_data[0])

    return id_list


class GetSTDaysForMoni(APIView):
    """
    """

    @staticmethod
    def get(request, *args, **kwargs):
        # print(request.query_params)
        _code = request.query_params["code"]
        _his_day_size = int(request.query_params["his_day_size"])
        _moni_day_size = int(request.query_params["moni_day_size"])
        _predict_day_size = int(
            request.query_params["predict_day_size"]) if "predict_day_size" in request.query_params else 0
        _random = int(request.query_params["random"])
        _random_size = int(request.query_params["random_size"])
        # http://127.0.0.1:18080/s_server/get_st_days_for_moni/?code=300684&his_day_size=120&moni_day_size=30&random=1&random_size=300
        data = {"code": _code,
                "his_day_size": _his_day_size,
                "moni_day_size": _moni_day_size,
                "predict_day_size": _predict_day_size,
                "random": _random,
                "random_size": _random_size
                }

        records = Record.objects.filter(dm_id_id=_code).order_by("d").values("d")
        records = [d["d"] for d in records]
        # print(records)

        days_list = []
        if len(records) < _his_day_size + _moni_day_size + _predict_day_size:
            data.update({"day_list": []})
        else:
            for i in range(0, len(records) - (_his_day_size + _moni_day_size + _predict_day_size) + 1):
                d_list = records[i:i + _his_day_size + _moni_day_size + _predict_day_size]
                days_list.append((d_list[0:_his_day_size],
                                  d_list[_his_day_size: _his_day_size + _moni_day_size],
                                  d_list[
                                  _his_day_size + _moni_day_size: _his_day_size + _moni_day_size + _predict_day_size]
                                  ))

            if _random == 0:
                data.update({"day_list": days_list})
            else:
                data.update({"day_list": random_data(days_list, _random_size)})

        # for d in days_list:
        #     print(d)
        return Response(data=data)


class MoniCustomDays(APIView):
    """
    模拟运算
    """

    @staticmethod
    def post(request, *args, **kwargs):
        try:
            ODData = OriginData()
            # print(request.data)
            _code = request.data["code"]
            _day_list = request.data["day_list"]
            _all_money = request.data["all_money"]
            _times_percent = request.data["times_percent"]
            _a_times = float(request.data["at"])
            _b_times = float(request.data["bt"])
            _moni_compute_days = [int(i) for i in request.data["moni_compute_days"].split(",")]
            # _predict_day_size = request.data["predict_day_size"]
            moni_results = []
            features = []
            for day_data in _day_list:
                data = {"code": _code,
                        "start_compute_day": day_data[0][0],
                        "end_compute_day": day_data[0][-1],
                        "compute_days": day_data[0],
                        "start_moni_day": day_data[1][0],
                        "end_moni_day": day_data[1][-1],
                        "moni_days": day_data[1],
                        "all_money": _all_money,
                        "times_percent": _times_percent,
                        "a_times": _a_times,
                        "b_times": _b_times,
                        "moni_compute_days": _moni_compute_days,
                        "predict_days": day_data[2]
                        }
                print("开始模拟的信息", data)
                last_all_money, last_zd_list, last_state_list, point_label,_,_ = moni_by_code_with_range_day(data)
                data.update({"last_money": last_all_money})
                data.update({"last_zd_list": last_zd_list})
                data.update({"last_state_list": last_state_list})

                # if float(last_all_money) > float(_all_money) * 1.00:
                #     data.update({"label": 1})
                # else:
                #     data.update({"label": 0})
                #
                data.update({"label": point_label})
                # zd 在先，laststate 在后
                feature = np.array([last_zd_list, last_state_list], dtype=np.float32)
                label = np.array([data["label"]])
                features.append((feature, label))

                moni_results.append(data)
            ODData.write_features(features)

            # print("结尾")
        except Exception:
            import traceback
            traceback.print_exc()
        return Response(data=moni_results)

class MoniCustomDaysNotWrite(APIView):
    """
    模拟运算
    """
    @staticmethod
    def post(request, *args, **kwargs):
        try:
            _code = request.data["code"]
            _day_list = request.data["day_list"]
            _all_money = request.data["all_money"]
            _times_percent = request.data["times_percent"]
            _a_times = float(request.data["at"])
            _b_times = float(request.data["bt"])
            _moni_compute_days = [int(i) for i in request.data["moni_compute_days"].split(",")]
            # _predict_day_size = request.data["predict_day_size"]
            moni_results = []
            features = []
            for day_data in _day_list:
                data = {"code": _code,
                        "start_compute_day": day_data[0][0],
                        "end_compute_day": day_data[0][-1],
                        "compute_days": day_data[0],
                        "start_moni_day": day_data[1][0],
                        "end_moni_day": day_data[1][-1],
                        "moni_days": day_data[1],
                        "all_money": _all_money,
                        "times_percent": _times_percent,
                        "a_times": _a_times,
                        "b_times": _b_times,
                        "moni_compute_days": _moni_compute_days,
                        "predict_days": day_data[2]
                        }
                print("开始模拟的信息", data)
                last_all_money, last_zd_list, last_state_list, point_label,could_moni_data, cloud_predict_data = moni_by_code_with_range_day(data)
                data.update({"last_money": last_all_money})
                data.update({"last_zd_list": last_zd_list})
                data.update({"last_state_list": last_state_list})
                data.update({"label": point_label})
                data.update({"could_moni_data": could_moni_data[-1]})
                data.update({"cloud_predict_data": cloud_predict_data})
                feature = np.array([last_zd_list, last_state_list], dtype=np.float32)
                label = np.array([data["label"]])
                features.append((feature, label))
                moni_results.append(data)

            # print("结尾")
        except Exception:
            import traceback
            traceback.print_exc()
        return Response(data=moni_results)
